package top.forgirl.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.forgirl.common.group.Insert;
import top.forgirl.common.group.Search;
import top.forgirl.common.group.Update;
import top.forgirl.common.result.Result;
import top.forgirl.common.result.ResultType;
import top.forgirl.domain.Demand;
import top.forgirl.domain.dto.DemandDo;
import top.forgirl.service.DemandService;

import java.util.List;

@RestController
@Api(tags = "需求记录管理模块")
public class DemandController {

    @Autowired
    public DemandService demandService;

    @ApiOperation(value = "查询需求记录", notes = "条件分页查询，当需要查询所有表记录时：请求路径为‘/demand/list/{offset}/0’，条件中demandDo.cId设值即可")
    @PostMapping("/demand/list/{offset}/{count}")
    public Result<List<Demand>> listDemand(@RequestBody @Validated({Search.class}) DemandDo demandDo,
                                           @PathVariable @ApiParam("页偏移量") int offset,
                                           @PathVariable @ApiParam("总数") int count) {
        System.out.println(demandDo);
        List<Demand> demands = demandService.list(demandDo, offset, count);
        return new Result<>(demands);
    }

    @ApiOperation("查询需求记录表的最大页数")
    @GetMapping("/demand/list/{cId}/{numOfPage}")
    public Result<Integer> getPageTotal(@PathVariable int numOfPage, @PathVariable String cId) {
        Integer pages = demandService.countPage(numOfPage, cId);
        return new Result<>(pages);
    }

    @ApiOperation("删除需求记录")
    @DeleteMapping("/demand")
    public Result deleteDemand(String cId, String dId) {
        Demand result = demandService.deleteDemand(cId, dId);
        if (result != null)
            return new Result(result);
        return new Result(ResultType.FAILED, "删除失败");
    }

    @ApiOperation("增加一条需求记录")
    @PostMapping("/demand")
    public Result addDemand(@RequestBody @Validated(Insert.class) DemandDo demandDo) {
        Demand result = demandService.insert(demandDo);
        if (result != null) {
            return new Result(result);
        }
        return new Result(ResultType.FAILED, "添加失败");
    }

    /**
     *
     * @param demand
     * @return 返回数据类型为Demand,不是DemandDo
     */
    @ApiOperation("修改需求记录")
    @PutMapping("/demand")
    public Result updateDemand(@RequestBody @Validated({Update.class}) Demand demand) {
        Demand result = demandService.update(demand);
        if (result != null) {
            return new Result(result);
        }
        return new Result(ResultType.FAILED, "更新失败");
    }
}
